package com.spring.demo.controller;

import com.google.common.collect.Lists;
import com.spring.demo.service.ResourceService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/sql")
public class SqlController {

    @Resource
    private ResourceService resourceService;

    @GetMapping("create")
    public List<String> createSql(String sql) {
        if (sql.endsWith(";")) {
            sql = sql.substring(0, sql.length() - 1);
        }
        List<String> list = resourceService.getList("data.txt");

        List<String> result = Lists.newArrayList();
        if (sql.startsWith("insert")) {
            String prefix = sql.substring(0, sql.indexOf("values") + 6);
            String suffix = sql.substring(sql.indexOf("values") + 6);
            List<List<String>> partition = Lists.partition(list, 100);
            for (List<String> stringList : partition) {
                StringBuilder sb = new StringBuilder();
                for (String line : stringList) {
                    sb.append(getString(line, suffix));
                }
                result.add(prefix + sb + ";");
            }
        } else {
            for (String line : list) {
                result.add(getString(line, sql) + ";");
            }
        }
        return result;
    }

    private static String getString(String line, String suffix) {
        String[] split = line.split("\t");
        for (String column : split) {
            suffix = suffix.replaceFirst("\\?", "'" + column + "''");
        }
        return suffix;
    }
}
